import os
import threading
import time

import requests
from flet import SnackBar, Text
from requests_html import HTMLSession as _HTMLSession, HTMLResponse
from typing import Optional

DESKTOP = os.path.join(os.path.expanduser("~"), "Desktop")


# 创建并启动一个新的线程来执行传入的函数 func。
# 这个线程会在指定的 timeout 时间后执行 func。
# 如果 func 执行过程中抛出异常，它会被捕获并打印出来
def one_shot_thread(func, timeout=0.0):
    def run():
        time.sleep(timeout)
        try:
            func()
        except Exception as e:
            print(f"one_shot_thread:{func.__name__} {e}")

    thread = threading.Thread(target=run)
    thread.daemon = True
    thread.start()


Threads = []


def snack_bar(page, message):
    page.snack_bar = SnackBar(content=Text(message), action="好的")
    page.snack_bar.open = True
    page.update()


"""
创建文件夹，如果不在则创建，存在跳过不处理
"""
def mkdir(folder_path):
    # 检查文件夹是否存在
    if not os.path.exists(str(folder_path)):
        # 如果文件夹不存在，则创建
        os.makedirs(str(folder_path))
        print(f"文件夹 {folder_path} 已创建。")
    else:
        print(f"文件夹 {folder_path} 已存在。")

class HTMLSession(_HTMLSession):
    def __init__(self, headers: Optional[dict] = None, **kwargs):
        super(HTMLSession, self).__init__(**kwargs)
        if headers:
            self.headers.update(headers)


def ms_to_time(ms):
    # 毫秒转换为时间格式
    ms = int(ms)
    minute, second = divmod(ms / 1000, 60)
    minute = min(99, minute)
    return "%02d:%02d" % (minute, second)


def handle_redirect(url, session=None):
    if session is None:
        session = HTMLSession()
    resp = session.get(url, stream=True)
    return resp.url


def download_url_content(url) -> HTMLResponse:
    session = HTMLSession()
    resp = session.get(url)
    return resp

def base32_encode_py(str_input):
    base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
    bits = ""
    base32 = ""
    # 将每个字符转换为8位二进制字符串并拼接
    for i in range(len(str_input)):
        bit = format(ord(str_input[i]), '08b')
        bits += bit
    # 填充0以确保长度是5的倍数
    while len(bits) % 5 != 0:
        bits += "0"
    # 将5位二进制字符串转换为一个Base32字符
    for i in range(0, len(bits), 5):
        chunk = bits[i:i+5]
        base32 += base32chars[int(chunk, 2)]
    # 填充以确保长度是8的倍数
    while len(base32) % 8 != 0:
        base32 += "="
    # 将填充字符 '=' 替换为 'HiFiNiYINYUECICHANG'
    return base32.replace('=', 'HiFiNiYINYUECICHANG')
def generateParam(data):
    key = '95wwwHiFiNicom27'
    outText = ''
    for i, char in enumerate(data):
        j = i % len(key)
        outText += chr(ord(char) ^ ord(key[j]))
    return base32_encode_py(outText)


def is_url_accessible(url):
    try:
        response = requests.head(url, allow_redirects=True, timeout=5)
        # 如果URL可达，至少返回的状态码应为200
        return response.status_code == 200
    except requests.RequestException:
        # 如果请求异常（如超时、连接错误等），则URL不可达
        return False